<?php

class Core_Api_Layout
{

    /**
     * get structure of Section of specific page & site
     * @param string $region
     * @param string $action_id
     * @param string $side [front-end, admin, email]
     */
    public function getStructure($region, $action_id = NULL, $side = NULL, $site_id = NULL)
    {

        if (NULL == $site_id)
        {
            $site_id = Nuo::getSiteId();
        }

        if (NULL == $action_id)
        {
            $action_id = Nuo::getPageName();
        }

        if (NULL == $side)
        {
            $side = Nuo::getMode() == 'admin' ? 'admin' : 'front-end';
        }

        $table = Nuo::getTable('core@layout');

        $select = $table -> select() -> where('site_id=?', $site_id) -> where('layout_side=?', $side) -> where('layout_region=?', $region) -> where('action_id=?', $action_id);

        // cache all element of this pharse
        $row = $table -> fetchRow($select);

        if (!is_object($row))
        {
            $select = $table -> select() -> where('site_id=?', $site_id) -> where('layout_side=?', $side) -> where('layout_region=?', $region);
            $row = $table -> fetchRow($select);
        }

        $eles = $row -> getElements();

        $result = $row -> toArray();

        return array(
            $this -> parepareArea($eles),
            $row -> toArray()
        );
    }

    public function parepareArea($blocks)
    {
        // group all block as needed.
        $result = array();

        foreach ($blocks as $block)
        {
            if (0 == $block['block_parent_id'] && $block['block_area'])
            {
                $region = $block['block_area'];
                $result[$region][] = $this -> prepareBlock($block);
            }
        }

        // refind children list

        return $result;
    }

    public function prepareBlock($block)
    {
        $cls = trim($block['block_class']);
        $block['css_class'] = 'uiBlock uiBlock' . str_replace(array(
            '_',
            'Controller',
            'Block'
        ), '', $cls);
        $block['css_id'] = 'blockId-' . $block['block_id'];
        $block['children'] = array();
        return $block;
    }

}
